package com.yipin.neimeng.constant;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.FileReader;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class RSAUtils {
    /**
     * 使用RSA私钥解密加密的消息
     *
     * @param encryptedMessage 加密的消息
     * @param privateKeyString 私钥字符串（通常是Base64编码的）
     * @return 解密后的字符串
     * @throws Exception 如果解密过程中发生错误
     */
    public static String decryptByPrivateKey(String encryptedMessage, String privateKeyString) throws Exception {
        // 将Base64编码的私钥字符串转换为字节
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyString);

        // 根据PKCS#8标准生成私钥
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        // 初始化Cipher对象用于解密
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        // 将Base64编码的加密消息转换为字节
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedMessage);

        // 执行解密操作
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        // 将解密后的字节转换为字符串
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

}
